<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use app\ads\controller\Api;

use function Composer\Autoload\includeFile;

if (is_file(ROOT_PATH . '/vendor/autoload.php')) {
    require_once ROOT_PATH . '/vendor/autoload.php';
}
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 素材管理, 注意php版本要7.2以上
 * @Author 小邓
 * @DateTime 2022-11-10
 */
class MaterialAliUpload extends Admin {

	public function _initialize() {
		parent::_initialize();
    }
    // 得到临时授权密钥相关 /admin/material_ali_upload/sts
    public function sts(){
        $data = [
            'code' => 0,
            'msg'  => 'success',
            'data' => []
        ];
        $region = 'cn-hangzhou';
        //构建一个阿里云客户端，用于发起请求。
        //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
        AlibabaCloud::accessKeyClient('LTAI5tJHH32ipSUDNGDjFHPE', 'HulGYOcefXfmoQ7jJT0uF29HhfSBXe')
                                ->regionId( $region )
                                ->asDefaultClient();
        //设置参数，发起请求。
        try {
            $result = AlibabaCloud::rpc()
                                ->product('Sts')
                                ->scheme('https') // https | http
                                ->version('2015-04-01')
                                ->action('AssumeRole')
                                ->method('POST')
                                ->host('sts.aliyuncs.com')
                                ->options([
                                                'query' => [
                                                'RegionId' => "cn-hangzhou",
                                                'RoleArn' => "acs:ram::1234257245562449:role/kusheoss",
                                                'RoleSessionName' => "kusheoss",
                                                ],
                                            ])
                                ->request();
            $arr = $result->toArray();
            $dir = input('post.dir', 'img');
            $arr['Credentials']['ossurl'] = "https://ks-material.oss-cn-hangzhou.aliyuncs.com/".$dir."/".date('Ymd');
            $arr['Credentials']['bucket'] = "ks-material";
            $arr['Credentials']['region'] = "oss-".$region;
            $data['data'] = $arr['Credentials'];
            // print_r($result->toArray());
        } catch (ClientException $e) {
            $data['code'] = 403;
            $data['msg'] =  $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            $data['code'] = 403;
            $data['msg']  = $e->getErrorMessage() . PHP_EOL;
        } 
        return json($data);
    }
   
}